<template>
  <div>
    <p style="font-size: 30px;font-weight: 700;margin-top:0">学生客户自动分配策略组</p>
    <div class="group-box">
      <el-row>
        <el-col :span="12">
          <span style=" font-size: 24px;font-weight: 700;">排班导入：</span>
        </el-col>
        <el-col :span="12">
        <kt-button
          :label="$t('action.batchimport')"
          type="primary"
          perms="autoDistribution:student:batchimport"
          @click="customerManagerImport"
        ></kt-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <span style=" font-size: 24px;font-weight: 700;">是否允许自动分配（资源划分中的资源）：</span>
        </el-col>
        <el-col :span="12">
          <el-radio-group v-model="auto">
            <el-radio label="1" size="medium">是</el-radio>
            <el-radio label="2" size="medium">否</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <div v-if="auto==1">
        <el-row>
          <el-col :span="12">
            <span style=" font-size: 24px; font-weight: 700;">自动分配方式：</span>
          </el-col>
          <el-col :span="12">
            <el-radio-group v-model="radio">
              <el-radio label="2" size="medium">按部门分配</el-radio>
              <el-radio label="1" size="medium">按个人分配</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
        <DepartmentTable
          :datas="deptLevelData2"
          @inputChange="inputChange"
          @input2Change="input2Change"
          v-if="radio == 2"
          :num="num"
          :departloading='departloading'
        ></DepartmentTable>
        <PersonalTable  
        :datas="date" 
        :personloading='personloading'  
        :deptUserName="deptUserName2" 
        :num_p="num_p" v-if="radio == 1"
        ></PersonalTable>
      </div>
    </div>

    <div>
      <KtButton
        :label="$t('action.close')"
        perms="true"
        type="primary"
        size="medium"
        style="margin-right: 2%;"
        @click="closeSelectedTag"
      ></KtButton>
      <KtButton
        :label="$t('action.save')"
        perms="true"
        type="primary"
        size="medium"
        v-if="radio == 2&auto == 1"
        style="margin-top: 2%; "
        @click="saveDepart"
      ></KtButton>
      <KtButton
        :label="$t('action.save')"
        perms="true"
        type="primary"
        size="medium"
        v-if="radio ==1&auto == 1"
        style="margin-top: 2%; "
        @click="savePerson"
      ></KtButton> 
       <KtButton
        :label="$t('action.save')"
        perms="true"
        type="primary"
        size="medium"
        v-if="auto == 2"
        style="margin-top: 2%; "
        @click="saveAuto"
      ></KtButton>
    </div>


     <!--导入-->
    <el-dialog :title="'批量导入'" width="30%" :visible.sync="uploadOem" :close-on-click-modal="false">
      <el-form :model="form">
        <el-form-item>
          <el-upload
            ref="uploadExcel"
            :action="uploadUrl"
            :limit="limitNum"
            :auto-upload="false"
            accept=".xls"
            :before-upload="beforeUploadFile"
            :on-change="fileChange"
            :on-exceed="exceedFile"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
            :on-remove="handleRemove"
          >
            <el-button size="small" plain>选择文件上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls(Excel97-2004)文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="uploadOem = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" @click.native="uploadFile">{{$t('立即上传')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import PersonalTable from "@/views/Core/PersonalTable";
import DepartmentTable from "@/views/Core/DepartmentTable";
import KtButton from "@/views/Core/KtButton";
import { baseUrl } from "@/utils/global";
import axios from "axios";
export default {
  name: "Student",
  components: {
    PersonalTable,
    DepartmentTable,
    KtButton
  },
  data() {
    return {
      radio: "",
      auto: "",
      date: [],
      num: [], //部门分配数量
      num_p: [], //个人分配
      tableData: [],
      listCustomerAutomaticAssignStrategy: [],
      strategyConfigQueryStrategy_depart: [],
      deptLevelData: [],
      deptLevelData2: [],
      deptUserName: [],
      deptUserName2: [],
      personloading: true,
      departloading: true,
      uploadOem: false,
      form: {
        file: ""
      },
      uploadUrl: baseUrl + "/file/upload", //文件上传地址
      limitNum: 1, //上传最大个数
      baseUrl: baseUrl,
      fileList: [],
      uploadUrl: baseUrl + "/file/upload", //文件上传地址
      size: "mini"
    };
  },
  methods: {
    // 请求三级部门
    get_deptLevel3() {
      this.tableData = JSON.parse(localStorage.getItem("deptLevel3Student"));
      this.deptLevelData = JSON.parse(
        localStorage.getItem("deptLevel3Student")
      );
      this.date = JSON.parse(localStorage.getItem("deptLevel3Student"));

      this.date.forEach(item => {
        item.text = item.deptName;
        item.value = item.deptName;
      });
      this.get_strategyConfigQueryStrategy_depart();
    },
    // 按照部门查询分配策略
    get_strategyConfigQueryStrategy_depart() {
      this.$api.student
        .strategyConfigQueryStrategy({
          customerType: 1,
          belongToType: 2
        })
        .then(res => {
          this.num = res.listCustomerAutomaticAssignStrategy;
          this.deptLevelData.forEach((item_dept, index_dept) => {
            this.num.forEach((item_num, index_num) => {
              if (item_dept.id == item_num.toId) {
                item_dept.priority = item_num.priority;
                item_dept.num = item_num.num;
              }
            });
          });
          this.deptLevelData2 = this.deptLevelData;
          this.departloading = false;
        });
    },
    // 按照个人查询分配策略
    get_strategyConfigQueryStrategy_person() {
      this.$api.student
        .strategyConfigQueryStrategy({
          customerType: 1,
          belongToType: 1
        })
        .then(res => {
          this.num_p = res.listCustomerAutomaticAssignStrategy;

          this.deptUserName.forEach((item_dept, index_dept) => {
            this.num_p.forEach((item_num, index_num) => {
              if (item_dept.toId == item_num.toId) {
                item_dept.priority = item_num.priority;
                item_dept.num = item_num.num;
              }
            });
          });
          this.deptUserName2 = this.deptUserName;
          this.personloading = false;
        });
    },
    // 获取是否允许自动分配
    get_allow_student_autoware_assign() {
      this.$api.student
        .strategyConfigQueryConfig({
          names: "ALLOW_STUDENT_AUTOWARE_ASSIGN",
          type: 1
        })
        .then(res => {
          this.auto = res.customerAssignConfig[0].value;
        });
    },
    // 自动分配方式
    get_student_aotuware_assign_type() {
      this.$api.student
        .strategyConfigQueryConfig({
          names: "STUDENT_AUTOWARE_ASSIGN_TYPE",
          type: 1
        })
        .then(res => {
          this.radio = res.customerAssignConfig[0].value;
        });
    },
    // 优先级
    inputChange(params) {
      this.listCustomerAutomaticAssignStrategy = Object.assign({}, params.row);
    },
    // 分配条数
    input2Change(params) {
      this.listCustomerAutomaticAssignStrategy = Object.assign({}, params.row);
    },
    saveDepart() {
      this.$confirm("确定提交信息？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let aa = [];
        let bb = [];
        this.deptLevelData.forEach(item => {
          item.toId = item.id;
          if(item.nums){
            item.num=item.nums
          }
          if(item.prioritys){
            item.priority=item.prioritys
          }
        });
        let customerAssignConfigList = Object.assign({}, this.radio);
        let customerAssignConfigList2 = Object.assign({}, this.auto);
        aa.push(customerAssignConfigList);
        bb.push(customerAssignConfigList2);
        aa.forEach(item => {
          item.value = this.radio;
          item.name = "STUDENT_AUTOWARE_ASSIGN_TYPE";
        });
        bb.forEach(item => {
          item.value = this.auto;
          item.name = "ALLOW_STUDENT_AUTOWARE_ASSIGN";
        });
        this.deptLevelData.forEach(item => {
          delete item.id;
          delete item.children;
          delete item.createDate;
          delete item.creater;
          delete item.deptLevel;
          delete item.deptName;
          delete item.isDelete;
          delete item.parentId;
          delete item.deptType;
          delete item.text;
          delete item.value;
          if (!item.priority) {
            item.priority = 0;
          }
          if (!item.num) {
            item.num = 0;
          }
        });
        this.$api.student
          .strategyConfigSetStrategy({
            listCustomerAutomaticAssignStrategy: this.deptLevelData,
            customerType: 1,
            belongToType: 2
            //  customerType=1 学生客户 belongToType=2部门1个人
          })
          .then(res => {
            if (res.result == 2) {
              this.$message({ message: res.msg, type: "error" });
            } else {
              this.$message({ message: res.msg, type: "success" });
            }
          });
        this.$api.student
          .strategyConfigSetConfig({
            customerAssignConfigList: aa,
            type: 1
          })
          .then(res => {});
        this.$api.student
          .strategyConfigSetConfig({
            customerAssignConfigList: bb,
            type: 1
          })
          .then(res => {});
        this.get_deptLevel3();
      });
    },
    savePerson() {
      this.$confirm("确定提交信息？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let aa = [];
        let bb = [];
        this.tableData.forEach(item => {
          item.toId = item.id;
        });
        let customerAssignConfigList = Object.assign({}, this.auto);
        let customerAssignConfigList2 = Object.assign({}, this.radio);
        aa.push(customerAssignConfigList);
        bb.push(customerAssignConfigList2);
        aa.forEach(item => {
          item.value = item[0];
          item.name = "STUDENT_AUTOWARE_ASSIGN_TYPE";
        });
        bb.forEach(item => {
          item.value = item[0];
          item.name = "ALLOW_STUDENT_AUTOWARE_ASSIGN";
        });
        this.$api.student
          .strategyConfigSetConfig({
            customerAssignConfigList: aa,
            type: 1
          })
          .then(res => {});
        this.$api.student
          .strategyConfigSetConfig({
            customerAssignConfigList: bb,
            type: 1
          })
          .then(res => {});
        this.deptUserName.forEach(item => {
          if (!item.priority) {
            item.priority = 0;
          }
          if (!item.num) {
            item.num = 0;
          }
          if(item.nums){
            item.num=item.nums
          }
        if(item.prioritys){
          item.priority=item.prioritys
        }
        });
        this.$api.student
          .strategyConfigSetStrategy({
            listCustomerAutomaticAssignStrategy: this.deptUserName,
            customerType: 1,
            belongToType: 1
          })
          .then(res => {
            if (res.result == 2) {
              this.$message({ message: res.msg, type: "error" });
            } else {
              this.$message({ message: res.msg, type: "success" });
            }
          });
        this.get_deptLevel3();
      });
    },
    // 获取部门人员
    get_person() {
      this.$api.person
        .findPageStudent({ accountStatus: 1, isControlResource: 1 })
        .then(res => {
          this.deptUserName = res.userInfoList;
          this.deptUserName.forEach(item => {
            item.toId = item.id;
          });
          this.get_strategyConfigQueryStrategy_person();
        });
    },
    saveAuto() {
      this.$confirm("确定提交信息？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warnin··g"
      }).then(() => {
        let aa = [];
        let customerAssignConfigList = Object.assign({}, this.auto);
        aa.push(customerAssignConfigList);
        aa.forEach(item => {
          item.value = this.auto;
          item.name = "ALLOW_STUDENT_AUTOWARE_ASSIGN";
        });
        this.$api.student
          .strategyConfigSetConfig({
            customerAssignConfigList: aa,
            type: 1
          })
          .then(res => {
            if (res.result == 2) {
              this.$message({ message: res.msg, type: "error" });
            } else {
              this.$message({ message: "操作成功！", type: "success" });
            }
          });
        this.get_deptLevel3();
      });
    },
    isActive(route) {
      return route.path === this.$route.path;
    },
    closeSelectedTag(view) {
      this.$store.dispatch("delVisitedViews", this.$route).then(views => {
        if (this.isActive(this.$route)) {
          const latestView = views.slice(-1)[0];
          if (latestView) {
            this.$router.push(latestView);
          } else {
            this.$router.push("/");
          }
        }
      });
    },
    // 批量导入
    customerManagerImport: function() {
      this.uploadOem = true;
      if (this.form.file != "") {
        this.$refs.uploadExcel.clearFiles();
        this.form.file = "";
      }
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: "警告",
        message: `只能选择 ${
          this.limitNum
        } 个文件，当前共选择了 ${files.length + fileList.length} 个`
      });
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.form.file = file.raw;
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xls") {
        this.$notify.warning({
          title: "警告",
          message: `只能上传Excel97-2004（即后缀是.xls）的文件`
        });
      }
      1;
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.$refs.uploadExcel.clearFiles();
      this.form.file = "";
      this.$notify.success({
        title: "成功",
        message: `文件上传成功,数据处理中,稍后在我的消息中查看！`
      });
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$notify.error({
        title: "错误",
        message: `文件上传失败`
      });
    },
    uploadFile() {
      let formData = new FormData();
      formData.append("file", this.form.file);
      axios
        .post(this.uploadUrl, formData, {
          "Content-Type": "multipart/form-data"
        })
        .then(res => {
          if (res.data.result == 1) {
            this.handleSuccess();
            let path = res.data.fileUrl;
            this.$api.student
              .importStudentAssignStrategyList({ path: path })
              .then(res => {
                this.uploadOem = false;
                this.findPage(null);
              });
          } else {
            this.handleError();
          }
        });
    },
    // 删除上传列表操作
    handleRemove(file, fileList) {
      this.form.file = "";
    }
  },
  mounted() {
    this.get_deptLevel3();
    this.get_person();
    this.get_strategyConfigQueryStrategy_depart();
    this.get_allow_student_autoware_assign();
    this.get_student_aotuware_assign_type();
  }
};
</script>

<style lang="scss">
.el-table {
  display: block;
}
.has-gutter tr th {
  text-align: center;
}
.el-table__row td > .cell {
  text-align: center;
}
.group-box {
  width: 80%;
  margin: 0 auto;
  .el-row {
    margin: 3% 0;
    .el-col-12 {
      text-align: left;
    }
  }
}
</style>
<style lang='scss' scoped>
.el-row .el-col {
  margin-left: 0;
}
.container .el-radio-group .el-radio:first-child {
  display: inline-block;
}
</style>
